package weibo

import (
	"net/http"
	"net/url"
	"strings"

	"bytes"
	"compress/gzip"
	"fmt"
	"io/ioutil"
	"math/rand"
	"strconv"

	"github.com/PuerkitoBio/goquery"
	"github.com/bitly/go-simplejson"
)

var content1 []string

var content2 = []string{
	"题外话，再说一下超话：一定要回复，0评帖子系统会认为是水贴。每天转发或者发帖@阿芬五次，会给她增加热度。发帖加tag，最好同步到微博。",
}

var clientHeader = map[string]string{
	"Accept":          "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
	"Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
	//Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0
	"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36",
}

var commonHeader = map[string]string{
	"Accept-Encoding":  "gzip, deflate", //则接受的内容要gzip解压
	"Host":             "weibo.com",
	"Referer":          "http://weibo.com/p/100808a473fd8a93ee54443cca14bea11a8251/super_index", //当前请求是从哪个页面过来
	"X-Requested-With": "XMLHttpRequest",
	"Content-Type":     "application/x-www-form-urlencoded",
	"Connection":       "keep-alive",
}

func apply_client_common(header *http.Header) {
	for k, v := range clientHeader {
		header.Set(k, v)
	}
	for k, v := range commonHeader {
		header.Set(k, v)
	}
}

func (p *Processor) GetMid(page int) []string {
	Info("page: ", strconv.Itoa(page))

	urlStr := "http://weibo.com/p/100808a473fd8a93ee54443cca14bea11a8251/super_index?page=" + strconv.Itoa(page) + "#Pl_Core_MixedFeed__291"
	req, _ := http.NewRequest("GET", urlStr, nil)

	apply_client_common(&req.Header)
	req.Header.Set("Content-Length", "213")
	req.Header.Set("Cache-Control", "no-cache")

	resp, _ := p.client.Do(req)
	Debug("cookie req :", req.Cookies())
	Info("Get_mid", resp.Status)

	r, _ := gzip.NewReader(resp.Body)
	defer r.Close()
	doc, _ := ioutil.ReadAll(r)
	//Debug(string(doc))

	return get_mids_text(string(doc), "mid=\\\"", 16)

	//doc, _ := goquery.NewDocumentFromReader(strings.NewReader("<div   tbinfo=\"ouid=2701288720\" class=\"WB_cardwrap WB_feed_type S_bg2\" mid=\"4136326011472050\"  action-type=\"feed_list_item\" diss-data=\"filter_actionlog=\">"))
	//doc.Find("div.WB_cardwrap").Each(
	//	func(i int, s *goquery.Selection) {
	//		attr, _ := s.Attr("mid")
	//		//title := s.Find("i").Text()
	//		fmt.Printf(attr)
	//	},
	//)
}

func get_mids_text(s string, tag string, _len int) []string {
	var result []string
	tagLen := len(tag)

	for _index := 0; _index != -1; s = s[_index+tagLen+_len:] {
		_index = strings.Index(s, tag)
		if _index != -1 {
			r := []rune(s[_index:])
			result = append(result, string(r[tagLen:tagLen+_len])) //mid长度16
		}

	}

	return result
}

func GetTag(s string, tagStart, tagEnd string, last bool) string {
	if last {
		start := strings.LastIndex(s, tagStart)
		end := strings.Index(s[start+len(tagStart):], tagEnd)
		return s[start+len(tagStart): start+len(tagStart)+end]

	} else {
		start := strings.Index(s, tagStart)
		end := strings.Index(s[start+len(tagStart):], tagEnd)
		return s[start+len(tagStart): start+len(tagStart)+end]
	}
}

func (p *Processor) GetComment(mid string) string {
	_url := "http://weibo.com/aj/v6/comment/small?"
	var data = map[string]string{
		"ajwvr":            "6",
		"act":              "list",
		"mid":              mid,
		"uid":              p.uid, //当前登录的用户id
		"isMain":           "true",
		"dissDataFromFeed": "[object Object]",
		"ouid":             "2274664022",
		"location":         "page_100808_super_index",
		"__rnd":            Now(),
		"_t":               "0",
	}
	for k, v := range data {
		_url = _url + k + "=" + v + "&"
	}

	req, _ := http.NewRequest("GET", _url, nil)
	apply_client_common(&req.Header)
	req.Header.Set("Referer", "http://weibo.com/p/100808a473fd8a93ee54443cca14bea11a8251/super_index")

	resp, err := p.client.Do(req)
	if err != nil {
		println(err.Error())
		return "error"
	}
	defer resp.Body.Close()
	r, _ := gzip.NewReader(resp.Body)
	_data, _ := ioutil.ReadAll(r)
	Debug("GetComment", string(_data))

	js, _ := simplejson.NewJson(_data)
	_html, _ := js.Get("data").Get("html").String()

	var comments []string
	doc, _ := goquery.NewDocumentFromReader(strings.NewReader(_html))
	//Debug(doc.Html())
	doc.Find("div.WB_text").Each(
		func(i int, s *goquery.Selection) {
			text := s.Text()
			_index := strings.Index(text, "：")
			comments = append(comments, text[_index+len("："):])
		},
	)

	//若刚发的贴子没人评论
	if len(comments) == 0 {
		return content2[rand.Intn(len(content2))]
	}

	return comments[rand.Intn(len(comments))]
}

func (p *Processor) SendComment(mid, content string) {
	content = content + "  " + content1[rand.Intn(len(content1))]

	//转发概率控制在0.5以下
	forward := "0"
	if Param_forward == "1" && rand.Intn(25) < 8 {
		forward = "1"
	}

	//cid：当前评论id
	postData := url.Values{
		"act":              {"post"},
		"mid":              {mid},     //微博id
		"uid":              {p.uid},   //当前登录的用户id
		"forward":          {forward}, //1为转发，0为不转发
		"isroot":           {"0"},
		"content":          {content},
		"location":         {"page_100808_super_index"}, //不用变
		"module":           {"scommlist"},
		"group_source":     {""},
		"filter_actionlog": {""},
		"pdetail":          {"100808a473fd8a93ee54443cca14bea11a8251"},
		"_t":               {"0"},
	}
	//__rnd：当前时间减去1970.01.01，秒
	urlStr := "http://weibo.com/aj/v6/comment/add?ajwvr=6&__rnd=" + Now()
	req, _ := http.NewRequest("POST", urlStr, strings.NewReader(postData.Encode()))
	apply_client_common(&req.Header)
	req.Header.Set("Referer", "http://weibo.com/p/100808a473fd8a93ee54443cca14bea11a8251/super_index")

	resp, err := p.client.Do(req)
	if err != nil {
		println(err.Error())
		return
	}
	defer resp.Body.Close()
	Info("SendComment ", resp.Status, content)
}

func (p *Processor) Like(mid string) (is_del int) {
	urlStr := "http://weibo.com/aj/v6/like/add?ajwvr=6&__rnd=" + Now()
	postData := url.Values{
		"location":         {"page_100808_super_index"}, //不用变
		"filter_actionlog": {""},
		"version":          {"mini"},
		"qid":              {"heart"},
		"mid":              {mid}, //微博id
		"loc":              {"page_102803_home"},
		"_t":               {"0"},
	}
	req, _ := http.NewRequest("POST", urlStr, strings.NewReader(postData.Encode()))
	apply_client_common(&req.Header)
	req.Header.Set("Referer", "http://weibo.com/p/100808a473fd8a93ee54443cca14bea11a8251/super_index")

	resp, err := p.client.Do(req)
	if err != nil {
		println(err.Error())
		return
	}
	r, _ := gzip.NewReader(resp.Body)
	defer r.Close()
	b, _ := ioutil.ReadAll(r)
	Debug("like ", string(b))

	js, _ := simplejson.NewJson(b)
	is_del, _ = js.Get("data").Get("is_del").Int()
	return
}

func (p *Processor) SignIn() {
	urlStr := "http://weibo.com/p/aj/general/button?ajwvr=6&api=http://i.huati.weibo.com/aj/super/checkin&texta=%E7%AD%BE%E5%88%B0&textb=%E5%B7%B2%E7%AD%BE%E5%88%B0&status=0&id=100808a473fd8a93ee54443cca14bea11a8251&location=page_100808_super_index&__rnd=" + Now()
	b := p.Get(urlStr)
	js, _ := simplejson.NewJson(b)
	msg, _ := js.Get("msg").String()

	Info("SignIn msg: ", msg)
}

//微博热点
func (p *Processor) HotPoint() (title string, srcs []string) {
	urlStr := "http://d.weibo.com/623751_1?ajaxpagelet = 1&__ref = /623751_0&_t = FM_150278443673766"
	b := p.Get(urlStr)

	_html := GetTag(string(b), "\"html\":\"", "\"})", true)
	//返回报文一定要去转义
	_html = strings.Replace(_html, "\\\"", "\"", -1)
	_html = strings.Replace(_html, "\\/", "/", -1)
	_html = strings.Replace(_html, "\\n", "", -1)

	doc, _ := goquery.NewDocumentFromReader(strings.NewReader(_html))

	ss1, _ := doc.Find("div.info_box").First().Html()
	Debug(ss1)

	doc.Find("div.info_box").First().Each(
		func(i int, s *goquery.Selection) {
			title = s.Find("div.title").Text()
			title = title + "\n" + s.Find("div.text_cut").Text()
			s.Find("li.unlog_pic").Each(
				func(i int, s *goquery.Selection) {
					src, _ := s.Find("img").Attr("src")
					srcs = append(srcs, src)
				},
			)
		},
	)
	return
}

func (p *Processor) SendMiniBlog(title string) {
	dir_list, _ := ioutil.ReadDir("./tmp")
	for i, v := range dir_list {
		fmt.Println(i, "=", v.Name())
	}

	//
	//content, err := ioutil.ReadFile(filePath)
	//if err != nil {
	//	Fatal(err)
	//}
	//
	//postData := url.Values{}
	//postData.Set("image", base64.StdEncoding.EncodeToString(content)) //base64编码
	//postData.Set("language_type", "ENG")
	//postData.Set("detect_direction", "true")
	//
	//resp, _ := http.PostForm(BaseValidateUrl+"?access_token="+vc.access_token, postData)
	//defer resp.Body.Close()
	//
	//b, _ := ioutil.ReadAll(resp.Body)
	//Info(string(b))
	//js, _ := simplejson.NewJson(b)
	//log_id, _ = js.Get("log_id").Int()
	//words_result, _ := js.Get("words_result").Array() //"words_result": [ {"words": " TSINGTAO"}, {"words": "青島睥酒"} ] }
	//tmp := words_result[0].(map[string]interface{})
	//word = tmp["words"].(string)
	//word = strings.Replace(word, " ", "", -1)
	//Info("word", word) //对于interface{}，print只会打印其内存地址，所以要.(string)

	return
}

func ddd() {
	var b bytes.Buffer
	w := gzip.NewWriter(&b)
	defer w.Close()

	w.Write([]byte(""))
	w.Flush()
	fmt.Println("gzip size:", len(b.Bytes()))

	r, _ := gzip.NewReader(&b)
	defer r.Close()
	undatas, _ := ioutil.ReadAll(r)
	fmt.Println("ungzip size:", len(undatas))
}
